import { Inject, Provide, Scope, ScopeEnum } from "@midwayjs/core";
import { Utils } from "../utils";
import { Repository } from "typeorm";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { User } from "../entity/user.entity";
import * as md5 from "md5";

@Provide()
@Scope(ScopeEnum.Request, { allowDowngrade: true })
export class UserService {
  @Inject()
  utils: Utils;

  @InjectEntityModel(User)
  userModel: Repository<User>;

  async findUserById() {}

  async initSysUser() {}

  async findUserByAccountAndPassword(account: string, password: string) {
    // 1、密码MD5加密
    // 2、将账号和密码拼使用下划线拼接起来再MD5加密
    const _pwd = md5(password);
    const pwd = md5(account + "_" + _pwd);
    const user = await this.userModel.findOne({
      where: {
        account,
        password: pwd
      }
    });
    if (user) {
      return this.utils.service.success(user);
    } else {
      return this.utils.service.fail();
    }
  }

  async update(user: User) {
    const res = await this.userModel.save(user);
    return res;
  }
}
